﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Windows.Navigation;
using System.Text;
using System.Xml;
using System.Net.Sockets;
using System.IO;
using Microsoft.Live;
using Microsoft.Live.Controls;
using Microsoft.Phone.Shell;

namespace Whiteboard
{
    public partial class Login : PhoneApplicationPage
    {
        //Referred http://msdn.microsoft.com/en-us/library/live/hh826550.aspx

        private LiveConnectClient client;
        bool flag;
        string userEmail;
        private GeoCoordinateWatcher gcw = null;

        public Login()
        {
            InitializeComponent();

            // Provide the location to the AdControl for better targeting (optional).
            // This is done by starting a GeoCoordinateWatcher and waiting for the location to be available.
            // The callback will set the location into the ad. 
            // Note: The location may not be available in time for the first ad request.
            this.gcw = new GeoCoordinateWatcher();
            this.gcw.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(gcw_PositionChanged);
            this.gcw.Start();
        }

        private void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // Stop the GeoCoordinateWatcher now that we have the device location.
            this.gcw.Stop();

            adControl.Latitude = e.Position.Location.Latitude;
            adControl.Longitude = e.Position.Location.Longitude;
        }

        private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                client = new LiveConnectClient(e.Session);
                UserNameText.Text = "Signed in.";
                client.GetCompleted +=
                    new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
                client.GetAsync("me", null);
            }
            else
            {
                UserNameText.Text = "Not signed in.";
                client = null;
                ProfileStack.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string firstName = "";
                string lastName = "";
                if (e.Result.ContainsKey("first_name") ||
                    e.Result.ContainsKey("last_name"))
                {
                    if (e.Result.ContainsKey("first_name"))
                    {
                        if (e.Result["first_name"] != null)
                        {
                            firstName = e.Result["first_name"].ToString();
                        }
                    }
                    if (e.Result.ContainsKey("last_name"))
                    {
                        if (e.Result["last_name"] != null)
                        {
                            lastName = e.Result["last_name"].ToString();
                        }
                    }
                    if (e.Result.ContainsKey("emails"))
                    {
                        if (e.Result["emails"] != null)
                        {
                            Dictionary<string, object> emails = e.Result["emails"] as Dictionary<string, object>;
                            userEmail = emails["account"].ToString();
                        }
                    }
                    UserNameText.Text =
                        "Hello, " + firstName + " " + lastName + "!";
                }
                else
                {
                    UserNameText.Text = "Hello, signed-in user!";
                }
                ProfileStack.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                UserNameText.Text = "Error calling API: " +
                    e.Error.ToString();
            }
        }

        private void btnJoin_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

            if (e.Uri.Equals("/MainPage.xaml"))
            {
                phoneAppService.State["userEmail"] = userEmail;
                phoneAppService.State["client"] = client;
            }
            base.OnNavigatedFrom(e);
        }

        private void adControl_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
        {
            // MessageBox.Show(e.Error.Message);
        }
    } 
    
}

